<template>
    <div class="dashboard-container">
        <my-search :fields="fieldsList" :baseNumber="4" @onSearch="searchForm" @onReset="resetForm" />
        <div class="btn">
            <el-button type="info" plain size="mini" @click="addhyxxkHandle()">新增</el-button>
            <el-button type="info" plain size="mini" @click="del()">删除</el-button>
        </div>
        <div class="table-list">
            <my-table v-loading="loading" ref="myEltable" style="width: 100%" row-key="id" :showsummary="false" :columns="tableColumns" :tableData="tableDatas" :pageNum="queryObj.pageNo" :pageSize="queryObj.pageSize" :totalPage="total" :height="$store.state.app.windowHeight - 200" max-height="660px" :current="false" @onCurrentChange="changepageNo" @onPageSizeChange="changePageSize" highlight-current-row :ifSelect="true" @onSelectionChange="onSelectionChange" />

        </div>

        <!-- 上传组件隐藏 -->
        <el-upload style="display:none;" ref="uploadTemplate" class="upload-demo" :before-upload="beforeUpload" action drag :show-file-list="false" :http-request="httpRequest" :multiple="false" accept=".doc,.docx">
            <el-button size="small" type="primary" ref="uploadTemplate_btn">点击上传</el-button>
        </el-upload>

        <el-dialog title="文件预览" :visible.sync="dialogVisible" append-to-body width="1440px" destroy-on-close top="6vh">
            <div v-loading="dialogLoading" class="fileView">
                <div ref="fileView"></div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
                <el-button type="primary" @click="downFile()" size="mini" :disabled="dialogLoading">下载报告</el-button>
            </span>
        </el-dialog>

        <el-dialog title="新增" :visible.sync="adddialogVisible" width="600px" destroy-on-close top="6vh" :before-close="closehyxxkHandle">
            <div class="addContent" v-loading="adddialogloading">
                <el-form ref="form" :model="form" label-width="120px" size="mini" label-position="right">
                    <el-form-item label="行业类型">
                        <el-select v-model="form.hymc" placeholder="请选择行业类型" clearable>
                            <el-option label="请选择" value=""></el-option>
                            <el-option v-for="item in hyOption" :label="item.HYMC" :key="item.HY_DM" :value="item.HYMC"></el-option>

                        </el-select>
                    </el-form-item>
                    
                    <el-form-item label="行业报告附件">
                        <el-button size="mini" type="primary" @click="addhyxxk()">上传</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closehyxxkHandle()" size="mini">取 消</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { query_hyxxk, delete_hyxxk, query_hyxxk_att, upload_hyxxk, add_hyxxk } from '@/api/cxtj/zdsygl'
import { hylx } from '@/api/common'
import { getUserName } from '@/utils/auth'
export default {
    name: 'Dashboard',

    data() {
        return {
            loading: false,
            adddialogVisible: false,
            adddialogloading: false,
            form: {
                hymc: '',
            },
            fd: '',
            fieldsList: [
                {
                    label: '行业名称:',
                    field: 'hymc',
                    type: 'select',
                    options: [],
                    value: ''
                },


            ],
            hyOption: [],
            //右侧表格开始  行业名称、年度，行业报告、上传人、上传时间、操作
            tableColumns: [
                 {
                    label: '行业名称',
                    prop: 'hymc',
                    align: 'center',
                    minWidth: 120,
                    /*render: (h, params) => {
                        return <dict-tag options={this.dict.type.jtxx_qyxydj} value={params.row.nsrxydj} />;
                    }*/
                },

                 {
                    label: '行业报告',
                    prop: 'doc_name',
                    align: 'center',
                    halign: 'center',
                    minWidth: 275,
                    render: (h, params) => {
                        return <span style="color:#409EFF;text-decoration: underline;cursor: pointer;" onClick={() => this.queryDoc(params.row)}>{params.row.doc_name}</span>;
                    }
                },
                {
                    label: '上传人',
                    prop: 'upload_by',
                    align: 'center',
                    minWidth: 80,

                },
                {
                    label: '操作',
                    prop: 'caozuo',
                    align: 'center',
                    width: 150,
                    render: (h, params) => {
                        return (
                            <span>
                                <el-button type="text" onClick={() => this.upload(params.row)}>上传</el-button>
                            </span>
                        );
                    }
                }




            ],
            tableDatas: []
            , queryObj: {
                hymc: '', //公司名称

                pageNo: 1,
                pageSize: 20
            },
            total: 0,
            selectedRows: [],
            dialogVisible: false,
            dialogLoading: false,
            fileBlob: null,
            fileName: '',
            uploadId: '',
            uploadFlag: 0,
        }
    },
    computed: {
        ...mapGetters([
            'name'
        ])
    },
    mounted() {
        this.getTableData();
        this.gethylx()
    },
    methods: {

        //获取行业类型
        gethylx() {

            hylx({
                "tableName": "dm_gy_hy",
                "where": " mlbz = 'Y'",
                "orderBy": "hy_dm"
            }).then(res => {
                console.log(res)
                this.hyOption = res.data
                this.fieldsList[0].options = res.data.map(item => {
                    return { value: item.HYMC, label: item.HYMC }
                })
            })
        },
        searchForm(params) {
            console.log(params, '查询条件');
            this.queryObj.hymc = params.hymc || '';
            this.getTableData();
        },
        resetForm() {
            for (let key in this.queryObj) {
                if (key == 'pageNo') {
                    this.queryObj[key] = 1;
                } else if (key == 'pageSize') {
                    this.queryObj[key] = 20;
                } else if (key == 'hymc') {
                    this.queryObj[key] = '';
                }
            }
            this.getTableData();
        },
        getTableData() {
            this.loading = true;
            let params = {
                hymc: this.queryObj.hymc,
                pageNum: this.queryObj.pageNo,
                pageSize: this.queryObj.pageSize,
            }
            query_hyxxk(params).then(res => {
                console.log(res)
                this.loading = false;
                if (res.code == 200) {
                    this.tableDatas = res.data.records
                    this.total = res.data.total
                }
            })
        },
        changepageNo(currPage) {
            this.queryObj.pageNo = currPage;
            this.getTableData();
        },
        changePageSize(pageSize) {
            this.queryObj.pageSize = pageSize;
            this.getTableData();
        },
        // 表格 多选 事件
        onSelectionChange(selectedRows) {
            this.selectedRows = selectedRows;
            console.log(selectedRows)
        },
        del() {
            if (this.selectedRows.length > 0) {
                this.loading = true;
                this.$confirm('该删除后将不可恢复，是否删除？', '友情提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    cancelButtonClass: 'JmconfirmCancelButton',
                    type: 'warning'
                }).then(() => {
                    let ids = []
                    this.selectedRows.forEach(item => {
                        ids.push(item.id)
                    })
                    delete_hyxxk(ids.join(',')).then(result => {
                        this.loading = false;
                        if (result && result.code == 200) {
                            this.$message.success('删除成功');
                            this.getTableData();
                        } else {
                            this.$message.error('删除数据失败！');
                        }
                    })
                        .catch(error => {
                            this.loading = false;
                        })
                })

            } else {
                this.$message.error('请选择一条数据删除');
                return false;
            }
        },

        addhyxxkHandle() {

            this.uploadFlag = 0
            this.adddialogVisible = true
            // this.$refs['uploadTemplate'].$refs['upload-inner'].handleClick()
        },
        closehyxxkHandle() {
            this.adddialogVisible = false
            this.form.hymc = ''
        },
        addhyxxk() {
            if (this.form.hymc == '') {
                this.$message.error('请选择行业类型！')
                return false
            } else {
                this.adddialogloading = true
                this.$refs['uploadTemplate'].$refs['upload-inner'].handleClick()
            }

        },

        queryDoc(data) {
            this.dialogVisible = true
            this.dialogLoading = true


            let fd = new FormData();
            fd.append("id", data.id);
            query_hyxxk_att(fd).then(res => {
                console.log(res)
                if (res.code == 200) {

                    this.dialogLoading = false
                    var raw = window.atob(res.data.file_data);
                    var uInt8Array = new Uint8Array(raw.length);
                    for (var i = 0; i < raw.length; i++) {
                        uInt8Array[i] = raw.charCodeAt(i);
                    }
                    const blob = new Blob([uInt8Array], {
                        type: "application/msword"
                    });
                    this.fileName = res.data.doc_name
                    this.fileBlob = blob
                    let docx = require("docx-preview");
                    this.$nextTick(() => {
                        docx.renderAsync(blob, this.$refs.fileView); // 渲染到页面
                    });
                }


            })
        },
         downFile() {
            if (this.fileBlob) {
                const elink = document.createElement("a");
                elink.download = this.fileName;
                elink.style.display = "none";
                elink.href = URL.createObjectURL(this.fileBlob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
            }
        },
        //上传doc附件
        //s上传名册
        upload(data) {
            this.uploadFlag = 1
            this.uploadId = data.id
            this.$refs['uploadTemplate'].$refs['upload-inner'].handleClick()
        },
        beforeUpload(file, fileList) {


            // if (file.size > 1024 * 1024 * 10) {
            //     this.$message.warning(
            //         "你上传的 \“" + file.name + "\” 文件过大，请上传小于2M的文件。"
            //     );
            //     return false;
            // }

            if (
                file.name.indexOf("@") != -1 ||
                file.name.indexOf("#") != -1 ||
                file.name.indexOf('""') != -1 ||
                file.name.indexOf("<") != -1 ||
                file.name.indexOf(">") != -1 ||
                file.name.indexOf("?") != -1 ||
                file.name.indexOf("|") != -1 ||
                file.name.indexOf("/") != -1 ||
                file.name.indexOf(":") != -1 ||
                file.name.indexOf("`\`") != -1
            ) {
                this.$message.warning(
                    "你上传的 \“" +
                    file.name +
                    "\” 文件有特殊字符，文件名中不可存在特殊字符,请重新上传"
                );
                return false;
            }

            let index = file.name.lastIndexOf(".");
            let Type = file.name.substr(index + 1, file.name.length);
            if (["doc", "docx"].indexOf(Type.toLowerCase()) === -1) {
                this.$message({
                    type: "warning",
                    message: "请上传后缀名为doc,docx的附件！",
                });
                return false;
            }
        },
        httpRequest(data) {
            console.log(data);
            let fd = new FormData();
            fd.append("file", data.file);

            if (this.uploadFlag === 0) {
                fd.append("hymc", this.form.hymc);
                // fd.append("nd", this.form.nd);
                add_hyxxk(fd).then(res => {
                    this.adddialogloading = false
                    if (res.code == 200) {

                        this.$message({
                            type: "success",
                            message: res.message,
                        });
                        this.getTableData()
                        this.closehyxxkHandle()

                    }
                })
            } else if (this.uploadFlag === 1) {
                fd.append("id", this.uploadId);

                upload_hyxxk(fd).then((res) => {
                    if (res.code == 200) {

                        this.$message({
                            type: "success",
                            message: res.message,
                        });
                        this.getTableData()

                    }
                });
            }
        },
    }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
    height: 100%;
    width: 100%;
    background-color: #fff;
    padding: 8px;

    .btn {
        padding: 8px 8px 8px 0;
    }
}
.fileView {
    width: 100%;
    height: 75vh;
    // overflow: hidden;
}
.addContent {
    width: 100%;
    height: 300px;
    padding: 20px;
}
</style>
